//package com.example.werewolf.controller;
//
//import com.example.werewolf.model.sse.SseDemo;
//import lombok.RequiredArgsConstructor;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.CrossOrigin;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
//
//import java.io.IOException;
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//
//@RestController
//@RequestMapping("/api/game")
//@RequiredArgsConstructor
//public class SseController {
//    private final ExecutorService executor = Executors.newCachedThreadPool();
//
//    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    @CrossOrigin(origins = "http://localhost:5173")
//    public SseEmitter handleSse() {
//        SseEmitter emitter = new SseEmitter(0L);
//
//        executor.submit(() -> {
//            try {
//                while (!Thread.currentThread().isInterrupted()) {
//                    String message = "当前时间: " + LocalDateTime.now()
//                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//
//                    SseDemo build = SseDemo.builder().userId(message).age(1).build();
//                    // 尝试发送消息
//                    emitter.send(SseEmitter.event().data(build));
//
//                    Thread.sleep(1000);
//                }
//            } catch (IOException e) {
//                // 客户端断开连接时会抛出 IOException
//                System.out.println("客户端断开连接: " + e.getMessage());
//            } catch (InterruptedException e) {
//                Thread.currentThread().interrupt();
//            } finally {
//                // 确保 emitter 被正确关闭
//                emitter.complete();
//            }
//        });
//
//        // 可选：注册回调（用于调试）
//        emitter.onCompletion(() -> System.out.println("SSE 连接完成"));
//        emitter.onTimeout(() -> {
//            System.out.println("SSE 超时");
//            emitter.complete();
//        });
//
//        return emitter;
//    }
//
//    @GetMapping("/test")
//    public String test() {
//        return "ok";
//    }
//}
